package guestbook;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;
import javax.servlet.http.*;
import javax.jdo.PersistenceManager;

import org.laowenchao.server.PMF;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;


public class SignGuestbookServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(SignGuestbookServlet.class.getName());

    public void doPost(HttpServletRequest request, HttpServletResponse resp)
                throws IOException {
    	
    	String ip = request.getHeader("x-forwarded-for");
    	if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	ip = request.getHeader("Proxy-Client-IP");
    	}
    	if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	ip = request.getHeader("WL-Proxy-Client-IP");
    	}
    	if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	ip = request.getRemoteAddr();
    	}
    	
    	String userAgent = request.getHeader("User-Agent");
    	
    	
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        String content = request.getParameter("content");
        boolean isAnonymous = false;
        if("yes".equals(request.getParameter("isAnonymous")))
        	isAnonymous = true;
        if (content == null) {
            content = "(No greeting)";
        }
        if (user != null) {
            log.info("Greeting posted by user " + user.getNickname() + ": " + content);
        } else {
            log.info("Greeting posted anonymously("+ip+"): " + content);
        }
        
        Date date = new Date();
        Greeting greeting = new Greeting(user, content, date,isAnonymous,ip,userAgent);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(greeting);
        } finally {
            pm.close();
        }
        
        resp.sendRedirect("/Guestbook.jsp");
    }
}